<!DOCTYPE html>
<html class="x-admin-sm" xmlns:th="http://www.thymeleaf.org">
<!--1、Head：标题、css-->
<head th:replace="admin_fragments :: head(用户列表)"></head>

<!--2、JS-->
<div th:replace="admin_fragments :: script"></div>

<!--3、内容-->
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body ">
                    <form class="layui-form layui-col-space5">
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="开始日" name="start" id="start">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="截止日" name="end" id="end">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input type="text" id="search_username" name="userName" placeholder="请输入用户名" autocomplete="off"
                                   class="layui-input">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <button class="layui-btn" id="search_btn" lay-submit="" lay-filter="sreach"><i
                                    class="layui-icon">&#xe615;</i></button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-header">
                    <button class="layui-btn layui-btn-danger" onclick="delAll()">
                        <i class="layui-icon"></i>批量删除
                    </button>
                    <button class="layui-btn" onclick="xadmin.open('添加用户','/user/page/userAddPage')"><i
                            class="layui-icon"></i>添加用户
                    </button>
                </div>
                <div class="layui-card-body ">
                    <!--数据表格-->
                    <table class="layui-hide" id="test" lay-filter="test"></table>
                </div>

            </div>
        </div>
    </div>
</div>

<script type="text/html" id="barDemo">
    <!--编辑-->
    <button type="button" class="layui-btn layui-btn-sm" lay-event="edit">
        <i class="layui-icon">&#xe642;</i>
    </button>
    <!--删除-->
    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">
        <i class="layui-icon">&#xe640;</i>
    </button>
</script>
<script>
    layui.use('table', function () {
        var table = layui.table;
        var $ = layui.jquery;

        table.render({
            elem: '#test'
            , url: '/user/page/queryAllUser'
            , title: '用户信息'
            , limits: [5, 10, 15, 20, 30]
            , limit: 5
            , done: function (res, curr, count) {
                console.log(res)
                $("table").css("width", "100%");
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left', width: 80}
                    , {
                    field: 'id',
                    title: '用户ID',
                    width: 100,
                    fixed: 'left',
                    unresize: true,
                    align: "center",
                    hide: true
                }
                    , {field: 'userName', title: '用户名', width: 100, align: "center", unresize: true}
                    , {field: 'userPassword', title: '密码', width: 100, align: "center", unresize: true}
                    , {field: 'userEmail', title: '邮箱', width: 150, align: "center", unresize: true}
                    , {field: 'userAge', title: '年龄', width: 100, align: "center", unresize: true}
                    , {
                    field: 'createTime', title: '创建时间', width: 120, align: "center", unresize: true,
                    templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}</div>"
                },
                    {
                        field: 'type', title: '角色', width: 100, align: "center", unresize: true,
                        templet: function (res) { //推荐
                            if (res.type == 1) {
                                return "<p>管理员</p>"
                            } else {
                                return "<p>用户</p>"
                            }
                        }
                    }
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 210, align: "center", unresize: true}
                ]
            ]
            , page: true
        });

        $(document).on('click', '#search_btn', function (data) {
            var searchUsername = $('#search_username');
            console.log(searchUsername.val())
            table.reload('test', {
                where: {
                    userName: searchUsername.val(),
                },
                page: {
                    curr: 1  //重新从第 1 页开始
                }
            });
        })

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            console.log(data);
            if (obj.event === 'del') {
                layer.confirm('确定要删除吗？', function (index) {
                    $.ajax({
                        type: 'post',
                        url: '/user/page/deleteUser', // ajax请求路径
                        data: {
                            userId: data.userId,
                        },
                        traditional: true,//这里设为true就可以了
                        success: function (data) {
                            if (data == 'true') {
                                layer.msg('删除成功！');
                            } else if (data == 'false') {
                                layer.msg('删除失败！');
                            }
                            layer.close(index);

                            table.reload('test', {
                                page: {
                                    curr: 1  //重新从第 1 页开始
                                }
                            });
                        }
                    });

                });
            } else if (obj.event === 'edit') {
                //页面层
                layer.open({
                    title: '修改：用户信息',
                    type: 2,
                    skin: 'layui-layer-rim', //加上边框
                    area: ['70%', '80%'], //宽高
                    content: '/user/page/userUpdateForm', //弹出的页面
                    //shadeClose: true, //点击遮罩关闭
                    btn: ['确定', '关闭'],
                    success: function (layer1, index) {
                        let body = layer.getChildFrame('body', index);
                        body.find(".userId").val(data.userId);   //通过class名进行获取数据
                        body.find(".oldUserName").val(data.userName);
                        body.find(".oldUserEmail").val(data.userEmail);
                        body.find(".oldUserPassword").val(data.userPassword);
                    },
                    yes: function (index, layero) {         //按了弹出层的确定按钮时，这是将在父窗口中获取子窗口form标签里的所有值，并根据name名和值形成键值对json对象
                        let body = layer.getChildFrame("body", index);
                        let data = {};
                        body.find("#changefileform").serializeArray().forEach(function (item) {    //获取弹出层写下的数据，input，下拉框啊，之类的表单元素（即changefileform下的所有数据）
                            data[item.name] = item.value;   //根据表单元素的name属性来获取数据
                        });
                        console.log(data)
                        if (data.newUserPassword != null && data.newUserPassword != '') {
                            $.post('/user/page/updateUser', data, function (result) {

                                if (result == "true") {
                                    layer.alert('修改成功：跳转登录页面！', {
                                        icon: 6,
                                        title: "提示",

                                    }, function () {
                                        window.parent.location.href = "/user";
                                    });
                                } else {
                                    layer.alert('修改失败, 请联系管理员。', {
                                        icon: 5,
                                        title: "提示"
                                    });
                                }
                            });
                        } else {
                            layer.alert('新密码：不能为空！!！', {
                                icon: 5,
                                title: "提示"
                            });
                        }

                        layer.close(index);
                    }
                });

            }
        });
    });       //末尾：结束

    //批量删除
    function delAll() {
        var checkStatus = layui.table.checkStatus("test");
        layer.confirm('确定要删除吗？', function (index) {
            var data = checkStatus.data;

            let array = [];
            data.forEach(e => {
                array.push(e.userId)        //将：选中行的id，依次添加到array数组
            })

            console.log(array)

            $.ajax({
                type: 'post',
                url: '/user/page/deleteAllUser', // ajax请求路径
                data: {
                    ids: array
                },
                traditional: true,//这里设为true就可以了
                success: function (data) {
                    if (data == 'true') {
                        layer.msg('用户批量删除成功！', {icon: 1});
                    } else if (data == 'false') {
                        layer.msg('用户批量删除失败！', {icon: 5});
                    }

                    layer.close(index);
                    layui.table.reload('test', {
                        page: {
                            curr: 1  //重新从第 1 页开始
                        }
                    });
                }
            });

        });
    }
</script>
</body>
</html>